/**
 * Copyright SunEEE Limited (c) 2015. All rights reserved.
 * This software is proprietary to and embodies the confidential
 * technology of SunEEE Limited.  Possession, use, or copying
 * of this software and media is authorized only pursuant to a
 * valid written license from SunEEE or an authorized sublicensor.
 */
package com.base.core.util;

import java.io.BufferedWriter;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;


import com.base.core.error.ErrorUtils;
import freemarker.cache.StringTemplateLoader;
import freemarker.ext.beans.BeansWrapper;
import freemarker.template.Configuration;
import freemarker.template.Template;

/**
 * ZhiLi:     Change to the actual description of this class
 * @version   Revision History
 * <pre>
 * Author     Version       Date        Changes
 * ZhiLi      1.0           2015年1月30日     Created
 *
 * </pre>
 * @since B2B1.0.0
 */

public abstract class TemplateUtils {
    
    private static final String TEMPLATE_NAME = "myTemplate";
    private static final String TEMPLATE_ENCODING= "UTF-8";
    private static Configuration cfg = null;
    
    private static Configuration getConfiguration(){
        if(cfg == null){
            cfg = new Configuration();
            //设置Freemarker默认编码，如果不设，FreeMarker在遇见中文操作系统时，会使用默认的GBK编码方式  
            cfg.setDefaultEncoding(TEMPLATE_ENCODING);
            cfg.setObjectWrapper(BeansWrapper.getDefaultInstance());
        }
        return cfg;
    }

    public static String generate(String template, Object context) {
        StringWriter stringWriter = new StringWriter(); 
        BufferedWriter writer = new BufferedWriter(stringWriter);
        try {
            //设置模板加载器---字符串 
            StringTemplateLoader templateLoader = new StringTemplateLoader();
            getConfiguration().setTemplateLoader(templateLoader);
            templateLoader.putTemplate(TEMPLATE_NAME, template);
            Template tl = cfg.getTemplate(TEMPLATE_NAME, TEMPLATE_ENCODING);
            
            tl.process(context, writer);
            
            return stringWriter.toString();
        } catch (Exception e) {
            throw ErrorUtils.wrap(e);
        }finally{
            try{
                writer.flush();  
                writer.close();
            }catch(Exception e){}
            try{
                stringWriter.flush();  
                stringWriter.close();
            }catch(Exception e){}
        }
    }

    public static void main(String[] args) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("code", "测试");
        System.out.println(TemplateUtils.generate("${code},是否正确", map));
    }
    
}
